# coding: utf-8

from leancloud import Object
from leancloud import File
from leancloud import Query
from leancloud import LeanCloudError
from leancloud import User
from flask import request
from datetime import datetime
import time
import os
from werkzeug.utils import secure_filename
import json

UPLOAD_FOLDER = '/tmp'  # leancloud engine 中,只有tmp目录下是具有可读功能的


class FarmerSayItem(Object):
    pass

class SayPub():
      # 发说说
    def publish(self):
        # for i in range(1, 4):
        #     self.upload("img"+str(i),"title"+str(i))
        print 'farmerPublish'
        return self.upload("name", "content")

    # 发说说中,上传图片的部分
    def upload(self, name, content):
        cont = request.form[content]
        farmerSayItem = FarmerSayItem(content=cont)
        nam = request.form[name]
        farmerSayItem.set("name", nam)
        uploaded_files = request.files.getlist("imgs")
        filenames = []
        num = 0
        for fil in uploaded_files:
            num += 1
            fname = secure_filename(fil.filename)
            filenames.append(fname)
            fil.save(os.path.join(UPLOAD_FOLDER, fname))
            file_object = open(UPLOAD_FOLDER + '/' + fname, 'r')
            upFile = File(fname, file_object)
            file_object.close()
            os.remove(UPLOAD_FOLDER + '/' + fname)
            upFile.save()
            farmerSayItem.set("img" + str(num), upFile)
            pass
        farmerSayItem.set('count', num)
        farmerSayItem.set('time', long(time.time() * 1000))
        farmerSayItem.save()
        result = {"code": 200, "message": "succecss"};
        return json.dumps(result)
        pass